﻿using AutoMapper;
using MediatR;
using RedDragon.Common.Domain.Process;
using RedDragon.Common.Infrastructure.Interface;
using RedDragon.ERP.ErroCodeEnum;
using T.Common.Domain.Common;

namespace RedDragon.ERP.API.Application.Commands.Proccess
{
    /// <summary>
    /// 获取工艺路线反填
    /// </summary>
    public class DetailsProcessRouteHandler : IRequestHandler<DetailsProcessRouteCommand, Result>
    {
        /// <summary>
        /// 工艺路线仓储
        /// </summary>
        private readonly IBaseRepository<ProcessRoutes> _processRouteRepository;

        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<DetailsProcessRouteHandler> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="processRouteRepository"></param>
        /// <param name="logger"></param>
        public DetailsProcessRouteHandler(IBaseRepository<ProcessRoutes> processRouteRepository,
                                      ILogger<DetailsProcessRouteHandler> logger)
        {
            _processRouteRepository = processRouteRepository;
            _logger = logger;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<Result> Handle(DetailsProcessRouteCommand request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CommonErrorCode.Search };
            try
            {
                //根据工艺路线编号获取数据
                var process = await (await _processRouteRepository.GetAll()).Where(p => p.ProcessRouteNo == request.ProcessRouteNo).FirstAsync();
                //数据不为空 
                if (process != null)
                {
                    result.Code = (int)CommonErrorCode.Success;
                    result.Data = process;
                    result.Msg = "获取工艺路线详情成功";
                }
            }
            catch (Exception ex)
            {
                result.Msg = "获取工艺路线详情异常" + ex.Message;
                _logger.LogError("获取工艺路线详情异常" + ex.Message);
            }
            return result;
        }
    }
}
